# -*- coding: utf-8 -*-

"""
@Remark: 用户地址管理
"""
import re
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from apps.project.models import *
from utils.jsonResponse import SuccessResponse,ErrorResponse
from rest_framework_simplejwt.authentication import JWTAuthentication
from utils.common import get_parameter_dic,REGEX_MOBILE
from django.core.cache import cache
from utils.locationanalysis import gettecentlnglat
from utils.serializers import CustomModelSerializer
from utils.viewset import CustomModelViewSet
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from django.db.models import Q,F
from utils.imageupload import CadUpload
import django_filters
from django_filters.filters import *
from django_filters.rest_framework import DjangoFilterBackend
from django_filters import utils
from django_filters.filters import CharFilter
from utils.rabbitmq import RabbitMQ
from utils.export_excel import export_sensor
import io
import xlwt
from django.http import HttpResponse

class ProjectSerializer(CustomModelSerializer):
    class Meta:
        model = Project
        fields = "__all__"
        read_only_fields = ["id"]

class ProjectCreateUpdateSerializer(CustomModelSerializer):
    class Meta:
        model = Project
        fields = '__all__'

class PojectManagerFilter(django_filters.rest_framework.FilterSet):
    # 模糊搜索
    name = django_filters.CharFilter(field_name='name', lookup_expr='icontains')  # icontains表示该字段模糊搜索
    #开始时间
    beginAt = django_filters.DateTimeFilter(field_name='create_datetime', lookup_expr='gte')  # 指定过滤的字段
    #结束时间
    endAt = django_filters.DateTimeFilter(field_name='create_datetime', lookup_expr='lte')
    # 精确搜索
    status = django_filters.CharFilter(field_name='status')  # 自定义过滤
    class Meta:
        model = Project
        fields = ['id', 'name', 'status', 'beginAt', 'endAt']

class ProjectViewSet(CustomModelViewSet):
    create_serializer_class = ProjectCreateUpdateSerializer
    update_serializer_class = ProjectCreateUpdateSerializer
    filterset_class = PojectManagerFilter
    queryset = Project.objects.all().order_by('-create_datetime')
    serializer_class = ProjectSerializer
    #filterset_fields = ['status','name','id']
    #search_fields = ('name')
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]
    
    def upload(self, request, *args, **kwargs):
        result = CadUpload(request, "dwg")
        if result['code'] == 200:
            return SuccessResponse(data=result['img'], msg=result['msg'])
        else:
            return ErrorResponse(msg=result['msg'])
        
    def anslye(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        instance = Project.objects.filter(id=pk).first()
        RabbitMQ(instance.filename)
        return SuccessResponse(data=instance.data, msg='')
    
    def excel(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        instance = Project.objects.filter(id=pk).first()
        buffer = io.BytesIO()
        export_sensor(instance.data,buffer)
        # 创建 HTTP 响应
        response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = 'attachment; filename="example.xlsx"'
        # 将 BytesIO 对象中的数据作为响应内容发送
        response.write(buffer.getvalue())
        # 返回响应
        return response

